<?php
// 2020年2月17日21:42:31
namespace app\index\controller\wanlshop;

use addons\wanlshop\library\WanlPay\WanlPay;
use addons\wanlshop\library\WanlSdk\QRcode;
use app\admin\model\wanlshop\ShopEarnestLog;
use app\api\controller\Common;
use app\common\controller\Frontend;
use app\common\helpers\ImageUtil;
use app\common\library\token\driver\Redis;
use app\common\model\Config;
use fast\Http;
use think\Request;
use WanlPay\Yansongda\Pay;

/**
 * 审核
 * @internal
 */
class Entry extends Frontend
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    protected $layout = 'default';
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\index\model\wanlshop\Auth;
		// 获取用户下的申请
        $this->entry = $this->model->where(['user_id' => $this->auth->id])->find();
        $this->view->assign("earnest_money", Config::getEarnestMoney());
        $this->view->assign("entry", $this->entry);
		$this->assignconfig("entry", $this->entry);
		// 获取用户手机号码
        $this->view->assign("mobile", $this->auth->mobile);
    }
    
    // 提交资质
    public function index()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
			$data['verify'] = '1';
			$data['user_id'] = $this->auth->id;
			$result = $this->entry ? $this->entry->allowField(true)->save($data) : $this->model->allowField(true)->save($data);
			$this->success();
			// $result ? $this->success() : $this->error(__('提交失败'));
        }
		// 如果已经提交过了
		if($this->entry){
			if ($this->entry->verify == '2' || $this->entry->verify == '3' || $this->entry->verify == '5') {
			    header('Location:' .url('/index/wanlshop/entry/stepfour'));
				exit;
			}
		}
		$this->view->assign('title', '商家入驻 - 步骤2 提交资质');
		return $this->view->fetch();
    }
    
    // 提交店铺信息
    public function stepthree()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $config = get_addon_config('wanlshop');
            $verify = $config['config']['store_audit'] == 'N' ? 3:2;
            // 更新提交信息
            $data['user_id'] = $this->auth->id;
            $data['verify'] = $verify;
			$this->entry ? $this->entry->allowField(true)->save($data) : $this->model->allowField(true)->save($data);
			// 自动审核
			if($config['config']['store_audit'] == 'N'){
			    $row = model('app\index\model\wanlshop\Auth')->where(['user_id' => $this->auth->id])->find();
				// 新增店铺
				$shop = model('app\index\model\wanlshop\Shop');
				$shop->user_id = $this->auth->id;
				$shop->state = $row['state'];
				$shop->shopname = $row['shopname'];
				$shop->avatar = $row['avatar'];
				$shop->bio = $row['content'];
				$shop->description = $row['bio'];
                $shop->phone = $row['mobile'];
				$shop->city = $row['city'];
                $shop->address = $row['address'];
                $shop->lng = $row['lng'];
                $shop->lat = $row['lat'];
				$shop->verify = $verify;
				// 新增店铺配置
				if($shop->save()){
					$config = model('app\index\model\wanlshop\ShopConfig');
					$config->shop_id = $shop->id;
					$config->save();
				}
			}
			$this->success();
			// $result ? $this->success() : $this->error(__('提交失败'));
        }
		$this->view->assign('title', '商家入驻 - 步骤3 提交店铺信息');
		return $this->view->fetch();
    }
    
    // 提交审核
    public function stepfour()
    {
        $this->view->assign('title', '商家审核');
        return $this->view->fetch();
    }

    // 获取保证金支付二维码
    public function addEarnestOrder(){

        $info =  ShopEarnestLog::get(['user_id'=>$this->auth->id]);
        if($info && $info['status'] == 'paid'){
            return json(array('msg'=>'已缴纳保证金'),0);
            exit;
        }
        $redis = \addons\wanlshop\library\WanlSdk\Common::redis();
        $key = 'shop_addEarnestOrder99_'.$this->auth->id;
        $img = $redis->get($key);
        if(!$img){

            if(!$info){
                $model = model('app\admin\model\wanlshop\ShopEarnestLog');
                $model->orderid = date("Ymdhis") . sprintf("%08d", $this->auth->id) . mt_rand(10000, 99999);
                $model->user_id = $this->auth->id;
                $model->amount = Config::getEarnestMoney();
                $model->payamount  = Config::getEarnestMoney();
                $model->paytype ='wechat';
                $model->save();
            } else{
                $info->orderid = date("Ymdhis") . sprintf("%08d", $this->auth->id) . mt_rand(10000, 99999);
                $info->amount = Config::getEarnestMoney();
                $info->payamount  = Config::getEarnestMoney();
                $info->save();
            }
            $info =  ShopEarnestLog::get(['user_id'=>$this->auth->id]);
            $data = [
                'out_trade_no' => $info->orderid, // 订单号
                'body' => '保证金', // 标题
                'total_fee' => round($info->payamount * 100,2), //付款金额 单位分
            ];

            $payConfig = (new WanlPay)->getConfig('wechat');
            $payConfig['notify_url'] = str_replace("notify", "notify_earnest", $payConfig['notify_url']);
            $wechat=  Pay::wechat($payConfig)->scan($data);

            if(isset($wechat['result_code']) && $wechat['result_code']== "SUCCESS") {
                $path ='uploads/earnest_img/';
                if(!file_exists($path)){
                    //检查是否有该文件夹，如果没有就创建，并给予最高权限
                    mkdir($path,0777,true);
                }
                //设置二维码文件名
                $filename = $path.md5($wechat['code_url']).'.png';

                if(!file_exists($filename)){
                    QRcode::png($wechat['code_url'], $filename, 'L', 4, 2);
                    ob_get_contents();
                    ob_end_clean();
                    $img = ImageUtil::handle('/'.$filename);
                    $redis->set($key,$img,60*60*2);
                }
            }
        }
        return json(array('img'=>$img,'code'=>1));
    }
}
